package controllers;

import com.google.appengine.api.taskqueue.Queue;
import com.google.appengine.api.taskqueue.QueueFactory;
import com.google.gdata.util.ServiceException;
import jobs.AlbumUpdateJob;
import jobs.AlbumsUpdateJob;
import models.Photo;
import models.PicasaAlbum;
import models.PicasaPhoto;
import play.Play;
import play.jobs.JobsPlugin;
import play.mvc.With;
import siena.PersistenceManager;
import siena.PersistenceManagerFactory;

import java.io.IOException;
import java.util.List;

import static com.google.appengine.api.taskqueue.TaskOptions.Builder.withUrl;

/**
 * Created by IntelliJ IDEA.
 * User: Cyril
 * Date: 07.08.11
 * Time: 0:15
 * To change this template use File | Settings | File Templates.
 */
@With(controllers.CustomSecure.class)
@Check("admin")
public class Picasa extends MenuBuilder {
    public static void index() throws ServiceException, IOException {
        List<PicasaAlbum> albums = PicasaAlbum.all().fetch();
        render(albums);
    }

    public static void album(Long id) throws IOException, ServiceException {
        PicasaAlbum album = PicasaAlbum.all()
                .filter("id", id)
                .get();
        renderArgs.put("lvl",
                Integer.valueOf(Play.configuration.getProperty("photo.size.level")));
        render(album);
    }

    public static void changePhotos(String id) {
        String[] photos = request.params.getAll("photo");
        PersistenceManager pm1 = PersistenceManagerFactory.getPersistenceManager(PicasaPhoto.class);
        PersistenceManager pm2 = PersistenceManagerFactory.getPersistenceManager(Photo.class);
        for (String pid : photos) {
            PicasaPhoto picasaPhoto = new PicasaPhoto();
            picasaPhoto.id = Long.valueOf(pid);
            pm1.get(picasaPhoto);
            if (picasaPhoto.photo == null) {
                picasaPhoto.photo = new Photo();
                picasaPhoto.photo.thumb = picasaPhoto.thumb;
                pm2.insert(picasaPhoto.photo);
            }
            pm1.update(picasaPhoto);
        }
        redirect("/Picasa/album?id=" + id);
    }

    public static void synchAlbums() throws Exception {
        AlbumsUpdateJob job = new AlbumsUpdateJob();
        if (JobsPlugin.executor == null)
            job.doJob();
        else {
            Queue queue = QueueFactory.getDefaultQueue();
            queue.add(withUrl("/synchr/albums"));
        }
        redirect("/Picasa/index");
    }

    public static void synchAlbum(String id) throws Exception {
        AlbumUpdateJob job = new AlbumUpdateJob(id);
        if (JobsPlugin.executor == null)
            job.doJob();
        else {
            Queue queue = QueueFactory.getDefaultQueue();
            queue.add(withUrl("/synchr/album").param("id", id));
        }
        redirect("/Picasa/album?id=" + id);
    }
}
